package com.sr.maven.filter;

import com.sr.maven.util.JDBCUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class TransactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //声明一个集合保存静态资源扩展名，非操作sql的 请求进入到这个过滤器 会浪费性能
    private static  Set<String> staticResourceExNameSet;

    static {

        staticResourceExNameSet = new HashSet<>();
        staticResourceExNameSet.add(".png");
        staticResourceExNameSet.add(".jpg");
        staticResourceExNameSet.add(".js");
        staticResourceExNameSet.add(".css");
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //前置操作，排除静态资源
       HttpServletRequest request = (HttpServletRequest)servletRequest;
       String servletPath = request.getServletPath();
       if(servletPath.contains(".")){
           String extName = servletPath.substring(servletPath.lastIndexOf("."));

           if (staticResourceExNameSet.contains(extName)) {
               //如果检测到当前请求确实是静态资源，则直接方形，不做事务操作
               filterChain.doFilter(servletRequest, servletResponse);
               return;
           }
       }

        //1.获取数据库连接
        Connection connection =null;
       //
        try {
            connection = JDBCUtils.getConnection();
            //关闭自动提交
            connection.setAutoCommit(false);
            //2.核心操作
            filterChain.doFilter(servletRequest,servletResponse);
            //3.提交事务
            connection.commit();

        }catch (Exception e){
            try {
                //4.回滚事务
                assert connection != null;
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            //页面显示：将这里捕获到的异常发送到指定页面
            String message = e.getMessage();
            request.setAttribute("message",message);
            request.getRequestDispatcher("/").forward(request,servletResponse);
        }
        finally {
            JDBCUtils.releaseConnection(connection);
        }
    }

    @Override
    public void destroy() {

    }
}
